import json
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework import filters
from django_filters.rest_framework import DjangoFilterBackend

from tasks.serializers import TasksSerializer
from tasks.models import Tasks
from utils.ansible_api import ANSRunner


class TasksViewset(viewsets.ModelViewSet):
    """
    create: 创建任务
    list: 获取任务列表
    retrieve: 获取任务信息
    update: 执行任务
    """
    queryset = Tasks.objects.all()
    serializer_class = TasksSerializer
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    search_fields = ('name',)
    ordering_fields = ('id',)

    def partial_update(self, request, *args, **kwargs):
        pk = int(kwargs.get('pk'))
        data = request.data
        task = Tasks.objects.get(pk=pk)
        rbt = ANSRunner()
        print(task.playbook.path)
        rbt.run_playbook(task.playbook.path)
        data['detail_result'] = json.dumps(rbt.get_playbook_result(), indent=4)
        print(data)
        Tasks.objects.filter(pk=pk).update(**data)
        return Response(status=status.HTTP_204_NO_CONTENT)
